use rocket::http::hyper::body::HttpBody;
use rocket::Route;
use rocket_db_pools::Connection;

use crate::ctx::mysql::MorTesting;
use crate::ctx::res::{Res, ToResult, Paging};
use crate::ctx::RouterLoader;
use crate::service::user::model::UserEntity;

pub(crate) struct UserService;

impl RouterLoader for UserService {
    fn loader() -> Vec<Route> {
        routes![handler, index]
    }
}

#[get("/?<id>")] // 路由属性
async fn index(id: Option<String>, mut db: Connection<MorTesting>) -> Res<UserEntity> {//请求处理程序
    return match id {
        None => {
            Res::failure_str("id is null")
        }
        Some(id_value) => {
            sqlx::query_as::<_, UserEntity>("SELECT * FROM tb_user where id = ? ")
                .bind(id_value)
                .fetch_one(&mut **db)
                .await
                .to_res()
        }
    };
}


#[get("/list", format = "json")]
async fn handler(paging: Paging, mut db: Connection<MorTesting>) -> Res<Vec<UserEntity>> {
    sqlx::query_as::<_, UserEntity>("SELECT * FROM tb_user  limit ?,?")
        .bind(paging.no)
        .bind(paging.size)
        .fetch_all(&mut **db)
        .await
        .to_res()
}